package com.book.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.book.result.Result;
import com.book.result.ResultEnum;
import com.book.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
@Order(-1)
public class UserLoginFilter implements GlobalFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Value("#{'${exclude.url}'.empty?null:'${exclude.url}'.split(',')}")
    private Set<String> urls;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getURI().getPath();
        for (String url : urls) {
            if(antPathMatcher.match(url,path)){
                //匹配    放行
                return chain.filter(exchange);
            }
        }
        //获取头中的token
        String first = request.getHeaders().getFirst("unauthorized");
        if(first==null||first.length()==0){
            return getMono(exchange);
        }
        //token存在   (时间过期，token错误)
        try {
            jwtUtil.parseJwt(first);
        } catch (Exception e) {
            return getMono(exchange);
        }

        return chain.filter(exchange);
    }

    private Mono<Void> getMono(ServerWebExchange exchange) {
        //没有登录
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        //放入状态码
        response.setStatusCode(HttpStatus.OK);
        //创建返回提示的对象
//        Result<Object> resultA = new Result<>(ResultContsent.LOGIN_ERROR_CODE, ResultContsent.LOGIN_ERROR_MSG);
        Result result = Result.respose(ResultEnum.LOGIN_ERROE);
        //设置响应头解决乱码问题
        response.getHeaders().add("Content-type","application/json;charset=utf-8");
        //result-----》Mono
        //将result转成字节数组
        byte[] bytes = JSONObject.toJSONBytes(result, SerializerFeature.NotWriteDefaultValue);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }
}
